package rs.ac.uns.ftn.informatika.mbs2.e11031.etaksi.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.interceptor.Interceptors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Interceptors(rs.ac.uns.ftn.informatika.mbs2.e11031.etaksi.pomocno.Beleznik.class)
public abstract class GenerickiDaoBean<T, Id extends Serializable> implements
		GenerickiDao<T, Id> {

	private Class<T> entitetskaKlasa;

	@PersistenceContext(unitName = "etaksi")
	protected EntityManager em;

	@SuppressWarnings("unchecked")
	public GenerickiDaoBean() {
		entitetskaKlasa = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public Class<T> getEntitetskaKlasa() {
		return entitetskaKlasa;
	}

	public T pronadjiPoId(Id id) {
		T entitet;
		entitet = em.find(entitetskaKlasa, id);
		return entitet;
	}

	@SuppressWarnings("unchecked")
	public List<T> pronadjiSve() {
		Query q = em.createQuery("select x from "
				+ entitetskaKlasa.getSimpleName() + " x");
		List<T> rezultat = q.getResultList();
		return rezultat;
	}

	@SuppressWarnings("unchecked")
	public List<T> pronadjiPo(String upit) {
		Query q = em.createQuery(upit);
		List<T> rezultat = q.getResultList();
		return rezultat;
	}

	public T sacuvaj(T entitet) {
		em.persist(entitet);
		return entitet;
	}

	public T stopi(T entitet) {
		entitet = em.merge(entitet);
		return entitet;
	}

	public void ukloni(T entitet) {
		entitet = em.merge(entitet);
		em.remove(entitet);
	}

	public void posalji() {
		em.flush();
	}

	public void ocisti() {
		em.clear();
	}

}
